import { Breadcrumb } from 'antd';
import { useEffect, useState } from 'react';
import { useLocation, Link } from 'react-router-dom';
import type { MenuItem } from '@/api/users';
import { useSelector } from 'react-redux';

interface BreadcrumbItem {
  path: string;
  name: string;
}

const MyBreadCrumb = () => {
  const location = useLocation();
  const [breadcrumbItems, setBreadcrumbItems] = useState<BreadcrumbItem[]>([]);
  // 从正确的 Redux state 路径获取菜单数据
  const menuData = useSelector((state: any) => state.auth.menuList);

  // 根据菜单数据查找路由名称
  const findMenuName = (path: string, menus: MenuItem[] | undefined): string | null => {
    // 检查 menus 是否存在且为数组
    if (!menus || !Array.isArray(menus)) {
      return null;
    }
    
    for (const menu of menus) {
      if (menu.key === path) {
        return menu.label;
      }
      if (menu.children) {
        const name = findMenuName(path, menu.children);
        if (name) return name;
      }
    }
    return null;
  };

  // 从菜单数据中获取名称
  const getNameFromMenu = (path: string): string | null => {
    return findMenuName(path, menuData);
  };

  useEffect(() => {
    // 根据当前路径生成面包屑导航项
    const pathSnippets = location.pathname.split('/').filter(i => i);
    
    const items: BreadcrumbItem[] = [];
    
    // 添加首页
    const homeName = getNameFromMenu('/') || '首页';
    items.push({
      path: '/',
      name: homeName
    });

    // 构建嵌套路径并查找对应名称
    let currentPath = '';
    pathSnippets.forEach((snippet) => {
      currentPath += `/${snippet}`;
      
      // 从菜单数据中查找对应名称
      const nameFromMenu = getNameFromMenu(currentPath);
      
      // 如果在菜单中没找到，则使用路径片段作为名称
      const name = nameFromMenu || snippet;
      
      items.push({
        path: currentPath,
        name: name
      });
    });

    setBreadcrumbItems(items);
  }, [location, menuData]);

  // 如果只有首页，则不显示面包屑
  if (breadcrumbItems.length <= 1) {
    return null;
  }

  // 使用 items 属性而不是 Breadcrumb.Item 组件（解决 Antd 警告）
  const breadcrumbItemsForAntd = breadcrumbItems.map((item, index) => {
    const isLast = index === breadcrumbItems.length - 1;
    
    return {
      title: isLast ? item.name : <Link to={item.path}>{item.name}</Link>
    };
  });

  return (
    <Breadcrumb 
      className="breadcrumb mt-3 mb-3"
      items={breadcrumbItemsForAntd}
      separator="/"
    />
  );
};

export default MyBreadCrumb;